import 'dart:io';

import 'package:demo/constants/route_location.dart';
import 'package:demo/constants/sp_key.dart';
import 'package:demo/core/plugin_registrant.dart';
import 'package:demo/core/router/app_router_delegate.dart';
import 'package:demo/mixin/after_layout_build_mixin.dart';
import 'package:demo/utils/dialog.dart';
import 'package:demo/utils/gesture.dart';
import 'package:demo/utils/native/security.dart';
import 'package:demo/utils/native/shared_preferences.dart';
import 'package:demo/widget/dialog/simple_confirm_or_cancel_dialog.dart';
import 'package:demo/widget/image/provider/native_image_provider.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> with AfterLayoutMixin {
  /// 隐私dialog
  late DialogUtils _dialogUtils = DialogUtils(context);

  /// 富文本协议点击事件
  late TapGestureRecognizer _privacyProtocolRecognizer = TapGestureRecognizer()..onTap = _openPrivateProtocol;

  @override
  void dispose() {
    _dialogUtils.dismiss();
    _dialogUtils.dispose();
    _privacyProtocolRecognizer.dispose();
    super.dispose();
  }

  @override
  void afterFirstLayoutBuild(BuildContext context) async {
    _checkSecurityAndPrivacyAgreement();
  }

  /// 检查安卓安全和隐私
  void _checkSecurityAndPrivacyAgreement() async {
    /// 检查是否使用了root权限 模拟器
    if (Platform.isAndroid) {
      final bool isRootPermission = await SecurityUtils.checkIsRoot;
      final bool isRunningInEmulator = await SecurityUtils.checkIsRunningInEmulator;
      if (isRootPermission) {
        _showRootPermissionDialog(isRunningInEmulator);
        return;
      }
      if (isRunningInEmulator) {
        _showIsRunningInEmulatorDialog();
        return;
      }
    }

    _showPrivacyAgreementDialog();
  }

  /// 显示隐私协议
  void _showPrivacyAgreementDialog() async {
    /// ios启动有判定是否第一次运行这个隐私页面
    if (Platform.isAndroid) {
      final bool? isAgree = await SharedPreferencesUtils.getBool(IS_AGREE_CONCEAL);
      if (isAgree == true) {
        _initAppAndForwardToRoot(needWriteSPFirstRun: false);
        return;
      }
    }
    _dialogUtils.setLayoutWidget(_buildPrivacyAgreementDialog);
    _dialogUtils.show();
  }

  /// 显示模拟器弹窗
  void _showIsRunningInEmulatorDialog() {
    _dialogUtils.setLayoutWidget(
      _buildSecurityTipsDialog(
        "风险提示",
        "当前检测App处于模拟器环境，是否继续使用?",
        () async {
          await _dialogUtils.dismiss(waitAnimatedRunningEnd: true);
          _showPrivacyAgreementDialog();
        },
      ),
    );
    _dialogUtils.show();
  }

  void _showRootPermissionDialog(bool isRunningInEmulator) {
    _dialogUtils.setLayoutWidget(
      _buildSecurityTipsDialog(
        "风险提示",
        "当前检测App处于Root权限环境，是否继续使用?",
        () async {
          await _dialogUtils.dismiss(waitAnimatedRunningEnd: true);
          if (isRunningInEmulator) {
            _showIsRunningInEmulatorDialog();
          } else {
            _showPrivacyAgreementDialog();
          }
        },
      ),
    );
    _dialogUtils.show();
  }

  /// 打开隐私协议
  void _openPrivateProtocol() {}

  /// 初始化并且前往root
  void _initAppAndForwardToRoot({bool needWriteSPFirstRun = true}) async {
    await _dialogUtils.dismiss(waitAnimatedRunningEnd: true, milliseconds: 180);
    if (needWriteSPFirstRun) {
      SharedPreferencesUtils.setBool(IS_AGREE_CONCEAL, true);
    }
    await AppRouterDelegate.of().setRoot(EXAMPLE_LIST);
    PluginRegistrant.instance.registerDartPlugins();
    PluginRegistrant.instance.registerNativePlugins();
  }

  /// 退出app
  void _exitApp() async {
    if (Platform.isAndroid) {
      await SystemNavigator.pop(animated: true);
    } else {
      exit(0);
    }
  }

  /// 协议弹窗
  Widget get _buildPrivacyAgreementDialog {
    return SimpleConfirmOrCancelDialog(
      contentPadding: const EdgeInsets.only(),
      title: "服务协议与用户隐私政策",
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 21),
          child: Text.rich(
            TextSpan(
              text: r"""欢迎使用flutter框架！
我们非常重视您的隐私保护和个人信息保护，我们特别提醒您再使用flutter框架服务前，仔细阅读并确认：""",
              children: [
                TextSpan(
                  text: "\n《flutter框架用户隐私权保护政策》\n",
                  style: const TextStyle(color: Colors.blueAccent),
                  recognizer: _privacyProtocolRecognizer,
                ),
                const TextSpan(
                  text: r"""
在您同意App隐私政策后，我们将进行集成SDK的初始化工作，会收集您的android_id Mac地址、IMEI、IMSI和应用安装列表，以保障App正常数据统计和安全风控。
我们将严格按照政策内容使用和保护您的个人信息，感谢您的信任。""",
                ),
              ],
            ),
            style: const TextStyle(
              height: 1.5,
              fontSize: 14,
              fontWeight: FontWeight.normal,
              color: Color(0xFF3A3C41),
            ),
          ),
        ),
      ],
      onLeftButtonClickListener: _exitApp,
      onRightButtonClickListener: GestureUtils.throttle(_initAppAndForwardToRoot),
    );
  }

  /// 风险提示弹窗
  Widget _buildSecurityTipsDialog(String title, String content, VoidCallback onRightButtonClickListener) {
    return SimpleConfirmOrCancelDialog(
      contentPadding: const EdgeInsets.only(),
      insetPadding: const EdgeInsets.symmetric(horizontal: 56, vertical: 24),
      title: title,
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 21),
          child: Text(
            content,
            textAlign: TextAlign.center,
            style: const TextStyle(
              height: 1.5,
              fontSize: 14,
              fontWeight: FontWeight.normal,
              color: Color(0xFF3A3C41),
            ),
          ),
        ),
      ],
      onLeftButtonClickListener: _exitApp,
      onRightButtonClickListener: GestureUtils.throttle(onRightButtonClickListener),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Image(
      image: NativeImageProvider("launch_image", defType: "mipmap", isIosSplashImage: Platform.isIOS),
      fit: BoxFit.fill,
    );
  }
}
